package com.dsunsoft.rtu.common.util;

import com.dsunsoft.rtu.common.constant.CommonConstants;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 签名加密工具类
 */
public class SignUtils {

    /**
     * 32位md5加密
     *
     * @param input 字符串
     * @return 加密后的字符串
     */
    public static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] result = digest.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder buffer = new StringBuilder();
        // 把每一个byte 做一个与运算 0xff;
        for (byte b : result) {
            // 与运算
            int number = b & 0xff;// 加盐
            String str = Integer.toHexString(number);
            if (str.length() == 1) {
                buffer.append("0");
            }
            buffer.append(str);
        }
        return buffer.toString();
    }

    /**
     * Base64编码.
     */
    public static String encodeBase64(byte[] input) {
        return new String(Base64.encodeBase64(input));
    }

    /**
     * Base64编码.
     *
     * @throws UnsupportedEncodingException
     */
    public static String encodeBase64(String input) throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64(input.getBytes(CommonConstants.UTF_8)));
    }

    /**
     * Base64解码.
     */
    public static byte[] decodeBase64(String input) {
        return Base64.decodeBase64(input.getBytes());
    }

    /**
     * Base64解码.
     */
    public static String decodeBase64String(String input) throws UnsupportedEncodingException {
        return new String(Base64.decodeBase64(input.getBytes()), CommonConstants.UTF_8);
    }
}
